// pages/home/article/article.js

const app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    userInfo: {},
    article: {},
    comments: [],
    inputValue: ''
  },

  onInput(event) {
    console.log("onInput", event);
    this.setData({
      inputValue: event.detail.value
    });
  },

  // 发表评论
  onPublish(event) {
    console.log("onPublish", event);

    if (this.data.inputValue == "") {
      return;
    }

    this.addComment();
    this.updateArticle();
  },

  addComment() {
    const curUserInfo = this.data.userInfo;
    var comment = {
      articleId:  this.data.article._id,
      content:    this.data.inputValue,
      time:       new Date().getTime(),
      userAvater: curUserInfo.avater,
      userId:     curUserInfo._id,
      userName:   curUserInfo.realName == "" ? curUserInfo.nickName : curUserInfo.realName
    };

    wx.cloud.callFunction({
      name: 'add_comment',
      data: {
        comment: comment
      },
      success: res => {
        console.log("add comment success", res);
      },
      fail: res => {
        console.log("add comment fail", res);
        wx.showToast({
          title: '发表评论失败',
          icon: 'error'
        });
      }
    });

    var commentList = this.data.comments;
    commentList.push(comment);
    this.setData({
      comments: commentList,
      inputValue: ''
    });
  },

  updateArticle() {
    let article = this.data.article;
    article.commentCount = this.data.comments.length;

    this.setData({ article: article});
    wx.cloud.callFunction({
      name: 'update_article',
      data: {
        article: article
      },
      success: res => {
        console.log("update article success", res);
      },
      fail: res => {
        console.log("update article fail", res);
      }
    })
  },

  // 生命周期函数--监听页面加载
  onLoad(options) {
    wx.showLoading({
      title: '数据加载中',
    });

    console.log("onLoad ", options);
    let article = JSON.parse(decodeURIComponent(options.article));

    this.setData({
      userInfo: app.globalData.userInfo,
      article: article,
      comments: []
    });

    // 获取该文章的评论
    var that = this;
    wx.cloud.callFunction({
      name: 'get_comments',
      data: {
        articleId: article._id
      },
      success: res => {
        console.log("get_comments success", res);

        that.setData({
          comments: res.result.data
        });
        wx.hideLoading();
      },
      fail: res => {
        console.log("get_comments fail", res);
        wx.hideLoading();
      }
    });

    console.log("this data", this.data);
  },

  // 生命周期函数--监听页面初次渲染完成
  onReady() { },

  // 生命周期函数--监听页面显示
  onShow() { },

  // 生命周期函数--监听页面隐藏
  onHide() { },

  // 生命周期函数--监听页面卸载
  onUnload() { },

  // 页面相关事件处理函数--监听用户下拉动作
  onPullDownRefresh() { },

  // 页面上拉触底事件的处理函数
  onReachBottom() { },

  // 用户点击右上角分享
  onShareAppMessage() { }
})